
<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>DheeShop 管理后台</h2>
        </div>
      </template>

      <el-form
          ref="formRef"
          :model="data.loginForm"
          :rules="data.rules"
          label-width="80px"
          @submit.prevent="login"
      >
        <el-form-item label="用户名" prop="adminName">
          <el-input
              v-model="data.loginForm.adminName"
              placeholder="请输入管理员用户名"
              prefix-icon="User"
          />
        </el-form-item>

        <el-form-item label="密码" prop="adminPass">
          <el-input
              v-model="data.loginForm.adminPass"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
              @keyup.enter="login"
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              :loading="loading"
              @click="login"
              style="width: 100%"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        
        <el-form-item class="register-form-item">
          <div class="register-link">
            <el-link type="primary" @click="handleRegister">注册账号</el-link>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../../util/request.js'
import router from '@/router/index.js'

export default {
  name: 'AdminLogin',
  setup() {
    const data = reactive({
      loginForm: {
        adminName: '',
        adminPass: ''
      },
      rules: {
        adminName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
        ],
        adminPass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      }
    })

    const formRef = ref()
    const loading = ref(false)

    const login = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        loading.value = true
        const res = await request.post('/admin/login', data.loginForm)

        if (res.data && res.data.code === 1) {
          const { token, adminId, adminName } = res.data.data
          
          // 存储到 localStorage
          localStorage.setItem('token', token)
          localStorage.setItem('adminId', adminId.toString())
          localStorage.setItem('adminName', adminName)

          
          ElMessage.success('登录成功')
          
          try {
            // 跳转到管理页面
            await router.push('/admin/members/list') // 直接跳转到成员列表页面
          } catch (error) {
            console.error('路由跳转失败:', error)
            ElMessage.error('跳转失败: ' + error.message)
          }
        } else {
          ElMessage.error(res.data?.msg || '登录失败')
        }
      } catch (error) {
        console.error('登录失败：', error)

        if (error.response) {
          // 服务器响应了错误状态码
          const status = error.response.status
          if (status === 401) {
            ElMessage.error('用户名或密码错误')
          } else if (status === 500) {
            ElMessage.error('服务器内部错误')
          } else {
            ElMessage.error(error.response.data?.msg || `请求失败 (${status})`)
          }
        } else if (error.request) {
          // 请求发出但没有收到响应
          ElMessage.error('网络连接失败，请检查网络连接')
        } else {
          // 其他错误
          ElMessage.error('登录失败，请稍后重试')
        }
      } finally {
        loading.value = false
      }
    }

    const handleRegister = () => {
      router.push('/admin/register')
    }

    // 组件挂载时清除可能存在的旧登录信息
    const clearOldLoginInfo = () => {
      localStorage.removeItem('token')
      localStorage.removeItem('adminId')
      localStorage.removeItem('adminName')
      console.log('已清除旧的登录信息')
    }

    // 在组件初始化时清除旧信息
    clearOldLoginInfo()

    return {
      data,
      formRef,
      loading,
      login,
      handleRegister
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-card {
  width: 420px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border-radius: 10px;
}

.card-header {
  text-align: center;
  padding: 10px 0;
}

.card-header h2 {
  margin: 0;
  color: #409eff;
  font-weight: 600;
  font-size: 24px;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  color: #606266;
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  border-radius: 6px;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 登录按钮样式 */
:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff, #667eea);
  border: none;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #337ecc, #5a67d8);
  transform: translateY(-1px);
}

/* 专门针对注册链接的样式 */
.register-form-item {
  margin-bottom: 0;
}

.register-link {
  text-align: right;
  width: 100%;
}

/* 使用深度选择器覆盖 Element Plus 默认样式 */
.register-form-item :deep(.el-form-item__content) {
  justify-content: flex-end;
}

/* 注册链接样式 */
:deep(.el-link--primary) {
  font-size: 14px;
}

:deep(.el-link--primary:hover) {
  color: #337ecc;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    width: 90%;
    margin: 0 20px;
  }
  
  .card-header h2 {
    font-size: 20px;
  }
}
</style>
